package com.lock.service;

import com.lock.entiy.Product;
import com.lock.mapper.ProductMapper;
import com.lock.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional
public class OptimisticLockService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * MyBatis-Plus乐观锁：扣减库存
     */
    public boolean decreaseStockByVersion(Long productId, int quantity) {
        int retryTimes = 3;

        for (int i = 0; i < retryTimes; i++) {
            Product product = productMapper.selectById(productId);
            if (product == null) {
                throw new RuntimeException("商品不存在");
            }

            if (product.getStock() < quantity) {
                return false;
            }

            product.setStock(product.getStock() - quantity);
            // 乐观锁：MyBatis-Plus会自动带上version条件
            int rows = productMapper.updateById(product);
            if (rows > 0) {
                return true; // 更新成功
            }

            System.out.println("版本冲突，重试第" + (i + 1) + "次");
        }

        return false;
    }

    /**
     * SQL乐观锁：扣减用户余额（通过WHERE条件实现）
     */
    public boolean decreaseBalance(Long userId, BigDecimal amount) {
        // 执行带条件的更新（余额 >= amount 时才更新）
        int rows = userMapper.decreaseBalance(userId, amount);
        return rows > 0; // 更新成功表示扣减成功
    }
}
